﻿using System;
using System.Collections.Generic;
using System.Text;
using DecodeInterface;
using System.Drawing;
using System.Windows.Forms;

namespace MotionDetect
{
    public class BackgroundModeling : DecodeBitmap
    {
        public byte[,] StableBackground { get; private set; }

        protected override unsafe object[] OnDecode(byte* pIn, byte* pOut, Size sizeIn, Size sizeOut, params object[] state)
        {
            if (StableBackground == null)
                StableBackground = new byte[sizeOut.Width, sizeOut.Height];

            for (int yOut = 0; yOut < sizeOut.Height; yOut++)
            {
                for (int xOut = 0; xOut < sizeOut.Width; xOut++)
                {
                    int index = (yOut * sizeOut.Width + xOut) * 3;
                    byte key = pIn[index];

                    byte maxKey = StableBackground[xOut, yOut];

                    if (maxKey == 0) 
                        StableBackground[xOut, yOut] = key;
                    else if (key > maxKey) 
                        StableBackground[xOut, yOut] += (byte)((key - maxKey + 14) / 15);
                    else if (key < maxKey)
                        StableBackground[xOut, yOut] -= (byte)((maxKey - key + 14) / 15);

                    pOut[index] =
                    pOut[index + 1] =
                    pOut[index + 2] =
                    Math.Min(Math.Max(StableBackground[xOut, yOut], byte.MinValue), byte.MaxValue);
                }
            }

            return new object[] { StableBackground };
        }
    }
}
